var x = document.getElementById("demo");
var map = null;
// min zoom to show markers.
var MIN_ZOOM = 14;
var STATIONS = "telOfanStations.js";
var bicycle = "images/bicycle_shop.png";
var infoWindow = null;

var gmap = {
    last_bounds: null,
    stattions: [],
    markers: [],
    my_marker: null,
    loaded_markers: false,
    my_latlng: null,
    
    onTilesLoaded: function(){
        // XXX this is if we want to update markers based on tiles view
        //      instead of loading all at once.
        var bounds = map.getBounds();
        if (!bounds || this.last_bounds == bounds)
            return;
        var zoom = map.getZoom();
        if (zoom < MIN_ZOOM)
            // TODO clear all markers.
            return;
        var val = bounds.toUrlValue();
        // TODO get markers in bounds from server.
        // TODO clear old markers and add new ones.
    },

    loadTelOfanStations: function() {
        var $this = this;
        $.getJSON('data/'+STATIONS, function(data) {
          $.each(data, function(index, value) {
            var latlng = new google.maps.LatLng(
              parseFloat(value.lat),
              parseFloat(value.lon));
            value.coordinates = latlng;
            $this.createMarker(latlng, value.shem_rechov, value.teur_mikum);
            $this.stattions.push(value);
          });
          
          $this.loaded_markers = true;
        });
    },
 
    createMarker: function(latlng, name, address) {
        var html = "<div class=\"infowindow-content\"><b>" + name + "</b> <br/>" + address+"</div>";
        var marker = new google.maps.Marker({
          map: map,
          position: latlng,
          icon: bicycle
        });
        google.maps.event.addListener(marker, 'click', function() {
          infoWindow.setContent(html);
          infoWindow.open(map, marker);
        });
        this.markers.push(marker);
    },
    
    refreshDistance: function() {
        for (var i = 0; i < this.markers.length; i++) {
            var marker = this.markers[i];
            marker.distance = google.maps.geometry.spherical.computeDistanceBetween(
              marker.position,
              this.my_marker.position
            );
        }
    },
    
    nearestMarker: function(){
        var _marker = null;
        for (var i = 0; i < this.markers.length; i++) {
            var marker = this.markers[i];
            if (!_marker || marker.distance < _marker.distance)
                _marker = marker;
        }
        // TODO nearest by distance is not nearest by road.
        //      one solution is to take X nearest points, get directions for
        //      all and then get shortest by walk.
        this.getDirectionsToMarker(this.my_marker.position, _marker.position);
    },
    
    getDirectionsToMarker: function(from_latlng, to_latlng) {
        var request = {
          origin: from_latlng,
          destination: to_latlng,
          travelMode: google.maps.TravelMode.WALKING
        };

        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            console.log(directionsDisplay);
          }
        });
    }
};

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(show_position);
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}

function showPosition(position) {
      x.innerHTML="Latitude: " + position.coords.latitude +
          "<br>Longitude: " + position.coords.longitude;
}

function initialize_map() {
    if (map)
        return;
    console.log("init map");
    var myOptions = {
	      zoom: 4,
	      mapTypeControl: true,
	      mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
	      navigationControl: false,
	      /*navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},*/
	      mapTypeId: google.maps.MapTypeId.ROADMAP      
    };

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    infoWindow = new google.maps.InfoWindow();
    
    var rendererOptions = {
      draggable: false,
      suppressMarkers: true
    };
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
    directionsService = new google.maps.DirectionsService();

    directionsDisplay.setMap(map);
    //TODO show directions in text.
    //directionsDisplay.setPanel(document.getElementById("directionsPanel"));
    
    google.maps.event.addListener(map, 'tilesloaded', function() {
        gmap.onTilesLoaded();
    });
    
    gmap.loadTelOfanStations();
}

function show_position(p) {
    //document.getElementById('current').innerHTML="latitude="+p.coords.latitude.toFixed(2)+" longitude="+p.coords.longitude.toFixed(2);
    var pos = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
    gmap.my_latlng = pos;
    
    _show_my_position();
}

function _show_my_position() {
    if (!map) {
        setTimeout(function(){_show_my_position();}, 1000);
        return;
    }
    
    map.setCenter(gmap.my_latlng);
    map.setZoom(14);

    var html = "<div class=\"infowindow-content\">this is me!</div>";

    var marker = new google.maps.Marker({
        position: gmap.my_latlng,
        map: map,
        title: "You are here"
    });
    
    gmap.my_marker = marker;

    google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
    });
    
    _show_nearest_marker();
}

function _show_nearest_marker() {
    if (!gmap.my_marker || !gmap.loaded_markers) {
        setTimeout(function(){_show_nearest_marker();}, 1000);
        return;
    }
    
    gmap.refreshDistance();
    gmap.nearestMarker();
}

$(document).delegate('#findNearestStation', 'pageinit', function(){
    initialize_map();
});
$(document).on("pageinit", function( event, ui ) {
    getLocation();
});
$(document).delegate('#findNearestStation', "pageshow", function( event, ui ) {
    google.maps.event.trigger(map, "resize");
});